// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,
  Popconfirm,
  Upload,
  message,
  Button,
  Modal,
  Row,
  Col,
  Input,
  Divider,
  Tooltip,
  Icon,
  Tabs,
  Spin,
  Select,
  DatePicker } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config' 
import Cookie from 'js-cookie'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './merchantListStyle.less' 
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
const { RangePicker } = DatePicker;
import moment from 'moment';
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
const FormItem = Form.Item
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}
const formItemLayoutTime = {
  labelCol: { span: 0 },
  wrapperCol: { span: 16 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const routeView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  // modelObj.xxx获取model中状态机的值
  let  {biz,regionList,modalObj,detail} = modelObj

  function updateModal(type,item){
    modalObj.visible = !modalObj.visible;
    if(type){
      modalObj.type = type;
    }else{
      modalObj.type = "";
    }
    form.resetFields();
    if(item){
      detail.id = item.id;
      detail.regionId = item.regionId;
      detail.name = item.name;
      detail.verifyPassword = item.verifyPassword;
    }else{
      detail = {};
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { modalObj,detail }
    })
  }

  function inputChange (value, name) {
    let obj = {[name]: value}
    detail = Object.assign(detail, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {detail}
    })
  }

  function addOrEditDetail(){
    form.validateFields((err, values) => {
		  if(!err){
        dispatch({
          type: `${namespace}/addOrEditDetail`,
          payload:{actionType:modalObj.type,resetFields}
        })
        modalObj.visible = !modalObj.visible;
        dispatch({
          type: `${namespace}/updateStore`,
          payload: {modalObj}
        })
		  }
		});
  }
  
  function deleteSkip(item){
    dispatch({
      type: `${namespace}/deleteFun`,
      payload: {item: item}
    })
  }
  
  // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'jfsc/admin/merchant/list',
      // 接口方式
      'method': 'POST',
      'app': '',
      // 接口参数
      'params': {uid:localStorage.getItem("username"),regionId:Cookie.get(config.cookie.regionId)},
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'regionId',
            zh_name: '区域名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: regionList
          }
        ],
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发

        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          // console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          // console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table': {
        'status_params': '',
        'status_text': '全部',
        'scroll': { x: 1300 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: 80,
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'regionName',
            'zh_name': '区域',
          },
          {
            'en_name': 'name',
            'zh_name': '商家名称',
          },
          {
            'en_name': 'verifyPassword',
            'zh_name': '核销密码',
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width: 120,
            fixed: 'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  <FlagBtn node={<a onClick={() => updateModal('edit', item)}>编辑<span className="ant-divider"  style={{ display: 'inline-block' }}/></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<Popconfirm Collapse title={`确定要删除吗？`} okText='确定' cancelText='取消' onConfirm={() => deleteSkip(item)}>
                      <a href='javascript:void(0)' onClick={(e) => {}}>删除
                          </a>
                  </Popconfirm>} btnId={''}> </FlagBtn>
                </span>
              )
            },
          }

        ],
        'actions': [
        ],
        "action_props": {
          fixed: "right",
          width: 210
        }
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新增',
          btnId: '',
          'type': 'primary',
          'onClick': (e) => {
            updateModal('add');
          }
        }
      ]
    },
  }

  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }
  
  return (
      <div className={cx('pageLayout')}>
        <ListPage pageProps={pageProps} />

        <Modal
        title={modalObj.type=='edit'?'编辑商家信息':modalObj.type=='add'?'新增商家信息':'查看'}
        width='460px'
        visible={modalObj.visible}
        onOk={() => { addOrEditDetail()}}
        onCancel={() => { updateModal() }}
      >
        <div className={styles.detailContainer}>
          <Form>
            <Row>
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="区域">
                  {getFieldDecorator('regionId', {
                    initialValue: detail.regionId ? detail.regionId : '',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请选择区域' }
                    ], 
                  })(<Select
                  onChange={(e) => inputChange(e, 'regionId')}>
                  {regionList.map((item,idx)=>{
                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                    })}
                  
                </Select>)}
                </FormItem>
              </Col>
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="商家名称">
                  {getFieldDecorator('name', {
                    initialValue: detail.name ? detail.name+'' : '',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请输入商家名称' },
                    ],
                  })(<Input
                    placeholder={'请输入商家名称'}
                    onChange={(e) => { inputChange(e.target.value, 'name') }}
                  />)}
                </FormItem>
              </Col>
              <Col span={18}>
                <FormItem
                  {...formItemLayout2}
                  label="核销密码">
                  {getFieldDecorator('verifyPassword', {
                    initialValue: detail.verifyPassword ? detail.verifyPassword+'' : '',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请输入核销密码' },
                      { pattern: /^(?:\d+|[a-zA-Z]+|[!@#$%^&*]+)$/, message: '请输入纯数字或纯字母' }
                    ],
                  })(<Input
                    placeholder={'请输入核销密码'}
                    onChange={(e) => { inputChange(e.target.value, 'verifyPassword') }}
                  />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>
      </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))